import Vue from 'vue'
import VueRouter from 'vue-router'
import home from './home'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Login',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../components/login.vue')
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import('../view/Home.vue'),
    redirect: '/users',
    children: home
  },
  {
    path: '*',
    meta: {
      title: 'error'
    },
    component: () => import('../view/error.vue')
  }
]

const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  // 如果用户访问的登录页面，直接放行
  // to 将要访问的路径
  // from 代表从哪个路径跳转而来
  // next 是一个函数，表示放行
  // next() 放行 next('/login') 强制跳转
  // debugger
  if (to.path === '/login') return next()
  // 从 sessionStorage 中获取到保存的 token 值
  const tokenStr = window.sessionStorage.getItem('token')
  // 没有 token，强制跳到登录页面
  if (!tokenStr) return next('/login')
  next()
})

export default router
